import { VitalForm, createForm, IVitalFormCtx, vitalConfigProvideKey } from 'vital';
import {
  MciButton,
  MciDialog,
  MciDropdown,
  MciDropdownItem,
  MciDropdownMenu,
  MciInput,
  MciMessageBox,
  MciRadio,
  MciRadioGroup
} from '@/components/base';
import { postWorkflowApprovalTaskComplete } from '@/api';
import { useApprovalProvide } from '@/components/business/Approval/index';
import { approvalRefreshEventName, TApprovalStatus, useAddSign } from '@/components/business/Approval/approval-helper';
import { useProcessBack } from '@/hooks/useProcessBack';
import * as i18n from '@/locales';
import { useDrawerStore } from '@/components/base/Drawer/store';
import { AddSignUser } from '../AddSignUser/index';
import { Teleport } from 'vue';
import './index.scss';
import { MciRichEditor } from '@/components/complex';
import emitter from '@numa/common/utils/emitter';
import { useTaskId } from '../../approval-helper/useTaskId';
import { useReissue } from '../../approval-helper/useReissue';
import { ILoadingCallback } from '@/components/base/Dialog';
import { useNode } from '../../approval-helper/useNode';

export const useApprovalType = () => {
  const approvalType = ref<TApprovalStatus>('AGREE');
  const text = computed(() => {
    switch (approvalType.value) {
      case 'AGREE':
        return i18n.t('确定同意吗？');
      case 'DISAGREE':
        return i18n.t('确定不同意吗？');
      default:
        return i18n.t('确定驳回吗？');
    }
  });
  const updateApprovalType = (type: TApprovalStatus) => {
    approvalType.value = type;
  };
  return {
    approvalType,
    updateApprovalType,
    text
  };
};
/**
 * 审批意见
 *
 * 底部的按钮组：
 * 1. 放大版的按钮全部展开， 标准版的按钮部分放入更多按钮的下拉中
 */
export const ApprovalComplete = defineComponent({
  name: 'ApprovalComplete',
  props: {
    maxEditorHeight: {
      type: String,
      default: '300px'
    },
    isFull: {
      type: Boolean,
      default: false
    }
  },
  emits: ['comment'],
  setup(props, { emit }) {
    const formRef = ref(null as TNullable<IVitalFormCtx<{ content: string }>>);
    const { backToProcess } = useProcessBack();
    const drawerStore = useDrawerStore();
    const { isAddSign } = useAddSign();
    const { isReissue } = useReissue();
    const { isTemplateFirstNode } = useNode();
    const { taskId } = useTaskId();
    const { isApprovalUser, isSubmitUser, completeHandleType, isComplete } = useApprovalProvide();

    const submitType = ref('success');

    const reissueModel = reactive({
      visible: false,
      type: '1',
      comment: '',
      handle: async (loadingCb?: ILoadingCallback) => {
        loadingCb?.(true);
        await postWorkflowApprovalTaskComplete({
          taskId: taskId.value,
          comment: reissueModel.comment,
          approvalStatus: 'AGREE',
          globalVariables: {
            CONTINUE: +reissueModel.type
          }
        }).finally(() => {
          loadingCb?.(false);
        });
        if (completeHandleType === 'close') {
          backToProcess('refresh');
        } else {
          emitter.emit(approvalRefreshEventName);
        }
      }
    });

    provide(vitalConfigProvideKey, { formMode: 'edit' });

    const addSignVisible = ref(false);

    const commentBtnVisible = computed(() => {
      return isApprovalUser.value || isSubmitUser.value;
    });
    const config = createForm({
      attrs: {
        hideRequiredAsterisk: false,
        labelPosition: 'top'
      },
      initModel: {
        content: ''
      },
      layout: {
        cols: 1
      },
      formItems: [
        {
          attrs: {
            label: i18n.t('审批意见'),
            rules: [
              {
                validator: (rule: TAnyFunction, val: string, cb: TAnyFunction) => {
                  if (submitType.value === 'success') {
                    return cb();
                  }
                  if (!val) {
                    return cb(new Error('请输入审批意见'));
                  }
                  cb();
                }
              }
            ]
          },
          // rulePresets: ['required'],
          fields: [
            {
              prop: 'content', //
              comp: (prop, model) => {
                return (
                  <MciRichEditor
                    v-model={model.content}
                    maxHeight={props.maxEditorHeight}
                    update-selection
                    onChange={() => {
                      drawerStore.changeModify(true);
                    }}
                    placeholder={i18n.t('请输入审批意见')}
                  />
                );
              }
            }
          ]
        }
      ]
    });

    const onComment = () => {
      emit('comment');
    };
    watch(isComplete, (isComplete) => {
      if (isComplete) {
        setTimeout(() => {
          drawerStore.changeModify(false);
        }, 100);
      }
    });

    return {
      config,
      formRef,
      taskId,
      drawerStore,
      addSignVisible,
      commentBtnVisible,
      isAddSign,
      submitType,
      completeHandleType,
      reissueModel,
      onComment,
      backToProcess,
      isTemplateFirstNode,
      isReissue,
      ...useApprovalType()
    };
  },
  render() {
    const {
      config,
      taskId,
      backToProcess,
      updateApprovalType,
      onComment,
      completeHandleType,
      formRef,
      reissueModel,
      isReissue,
      isTemplateFirstNode
    } = this;
    const btnSizeAttr = {
      size: 'small'
    };
    // 处理审批意见
    const confirmHandle = async () => {
      const { content } = formRef?.getModel() || {};
      await postWorkflowApprovalTaskComplete({
        taskId,
        comment: content || '',
        approvalStatus: this.approvalType
      });
      // console.log('completeHandleType', completeHandleType);
      if (completeHandleType === 'close') {
        backToProcess('refresh');
      } else {
        emitter.emit(approvalRefreshEventName);
      }
    };

    const showDialog = async (status: TApprovalStatus) => {
      /* 点击同意 & 重新发起的审批 & 第一个审批节点 */
      // console.log('status', status);
      if (isReissue && status === 'AGREE' && isTemplateFirstNode) {
        const { content } = formRef?.getModel() || {};
        reissueModel.comment = content || '';
        reissueModel.visible = true;
        return;
      }
      this.submitType = status === 'AGREE' ? 'success' : 'reject';
      await formRef?.validate();
      updateApprovalType(status);
      MciMessageBox.confirm(this.text, i18n.t('提示'), {
        requestLoading() {
          return confirmHandle();
        }
      });
    };
    const renderRejectBtn = () => {
      return (
        <MciButton class="flex-1 " {...btnSizeAttr} onClick={() => showDialog('REJECT')}>
          {i18n.t('驳回')}
        </MciButton>
      );
    };

    const createFlatButtons = () => {
      return (
        <>
          <MciButton type="primary" class="flex-1 " {...btnSizeAttr} onClick={() => showDialog('AGREE')}>
            {i18n.t('同意')}
          </MciButton>
          {renderRejectBtn()}
        </>
      );
    };

    const createDropdownButtons = () => {
      const sign = {
        command: 'sign',
        label: i18n.t('加签')
      };
      const comment = {
        command: 'comment',
        label: i18n.t('评论')
      };
      const configs: (typeof sign)[] = [];

      const handleReject = () => {
        // 存在不同意时，驳回按钮在dropdown 中
        const onRejectTrigger = () => {
          showDialog('REJECT');
        };
        return {
          onRejectTrigger
        };
      };

      const handleSign = () => {
        if (this.isAddSign) {
          configs.push(sign);
        }
        const onSignTrigger = () => {
          this.addSignVisible = true;
        };
        return {
          onSignTrigger
        };
      };

      const handleComment = () => {
        if (this.commentBtnVisible) {
          configs.push(comment);
        }
        const onCommentTrigger = () => {
          onComment();
        };
        return {
          onCommentTrigger
        };
      };
      const { onRejectTrigger } = handleReject();
      const { onSignTrigger } = handleSign();
      const { onCommentTrigger } = handleComment();

      const trigger = {
        sign: onSignTrigger,
        reject: onRejectTrigger,
        comment: onCommentTrigger
      };

      const onCommand = (command: keyof typeof trigger) => {
        trigger[command]?.();
      };

      if (!configs.length) {
        return null;
      }

      return (
        <MciDropdown
          onCommand={onCommand}
          placement="top"
          vSlots={{
            dropdown: () => (
              <MciDropdownMenu>
                {configs.map(({ label, command }) => {
                  return <MciDropdownItem command={command}> {label}</MciDropdownItem>;
                })}
              </MciDropdownMenu>
            ),
            default: () => (
              <MciButton type="info" link class="ml-8px">
                <span class="mci-icon-ellipsis"></span>
              </MciButton>
            )
          }}
        />
      );
    };

    // 放大版本的按钮组
    const createLargeGroup = () => {
      const renderAddSignBtn = () => {
        return (
          <MciButton type="info" link class="flex-1" {...btnSizeAttr} onClick={() => (this.addSignVisible = true)}>
            <span class="cr-grey-9">{i18n.t('加签')}</span>
          </MciButton>
        );
      };
      return (
        <>
          <MciButton type="primary" class="flex-1 " {...btnSizeAttr} onClick={() => showDialog('AGREE')}>
            {i18n.t('同意')}
          </MciButton>
          <MciButton class="flex-1 " {...btnSizeAttr} onClick={() => showDialog('REJECT')}>
            {i18n.t('驳回')}
          </MciButton>
          {this.isAddSign ? renderAddSignBtn() : ''}
          {this.commentBtnVisible ? (
            <MciButton class="flex-1" type="info" link {...btnSizeAttr} onClick={onComment}>
              {i18n.t('评论')}
            </MciButton>
          ) : (
            ''
          )}
        </>
      );
    };
    // 标准版本的按钮组
    const createSmallBtnGroup = () => {
      return (
        <>
          {createFlatButtons()}
          {createDropdownButtons()}
        </>
      );
    };
    return (
      <div class="approval-comment">
        <VitalForm ref="formRef" class="clear-right mt-16px" config={config} />
        <div class={`flex mt-8px small`}>{this.isFull ? createLargeGroup() : createSmallBtnGroup()}</div>
        <Teleport to="body">
          <AddSignUser v-model={this.addSignVisible} onClose={() => (this.addSignVisible = false)} />
        </Teleport>
        <MciDialog
          title="同意"
          vModel={reissueModel.visible}
          appendToBody
          width="600px"
          confirmHandle={reissueModel.handle}>
          <MciRadioGroup vModel={reissueModel.type}>
            <MciRadio label="1" text="同意且无需重走审批流" />
            <MciRadio label="0" text="同意且需重走审批流" />
          </MciRadioGroup>
          <MciRichEditor class="mt-24" placeholder="请输入原因" vModel={reissueModel.comment} />
        </MciDialog>
      </div>
    );
  }
});
